package com.example.ccj.u.server;

import androidx.annotation.NonNull;


import com.example.ccj.u.NetworkUtils;
import com.example.ccj.u.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class HeaderInterceptor implements Interceptor{
    public static Map<String,String> header = new HashMap<>();

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
//        Request.Builder builder = chain.request()
//                .newBuilder()
//                .cacheControl(new CacheControl.Builder().maxStale(2, TimeUnit.HOURS).build())
//                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
//                .addHeader("Accept-Encoding", "gzip, deflate")
//                .addHeader("Connection", "keep-alive")
//                .addHeader("Accept", "*/*")
                ;
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        //添加请求头
        if (header != null) {
            for (String key: header.keySet()) {
                String s = header.get(key);
                if (!StringUtils.isTrimEmpty(s)) {
                    builder.addHeader(key,s);
                }
            }
        }
        //读接口上的@Headers里的注解配置
        String cacheControl = request.cacheControl().toString();



        //没有网络,强制使用缓存.
        if (!NetworkUtils.isAvailable()) {
            builder.cacheControl(CacheControl.FORCE_CACHE);
        }

        if (!StringUtils.isEmpty(cacheControl)) {
            //响应头设置成无缓存
            builder.addHeader("Cache-Control", cacheControl).removeHeader("Pragma");
        }

//        if (!NetworkUtils.isAvailable() && !StringUtils.isEmpty(cacheControl)){
//            //重置请求体;
//            builder.cacheControl(CacheControl.FORCE_CACHE);
////            builder = chain.request().newBuilder().cacheControl(CacheControl.FORCE_CACHE);
//        }

        //如果没有添加注解,则不缓存
//        if (StringUtils.isEmpty(cacheControl) || "no-store" .contains(cacheControl)) {
//            //响应头设置成无缓存
//            cacheControl = "no-store";
//        }

//        builder.header("Cache-Control", cacheControl).removeHeader("Pragma");

        return chain.proceed(builder.build());
    }
}
